package com.zhan.drugStore.filter;

import cn.hutool.json.JSONUtil;
import com.zhan.drugStore.bean.bo.UserBO;
import com.zhan.drugStore.config.JwtToken;
import com.zhan.drugStore.constant.LogConstant;
import com.zhan.drugStore.enums.ResultEnum;
import com.zhan.drugStore.util.ResponseBase;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.MDC;
import org.springframework.http.HttpStatus;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 版权：点钢科技有限公司上海分公司
 * 功能：对请求进行jwt 拦截判断
 * 作者：詹银
 * 日期：2021/4/23
 */
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("access_token"); // 或者是 "access_token"
        return token != null;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        UserBO userBO = (UserBO) SecurityUtils.getSubject().getPrincipal();
        if (userBO != null) {
            MDC.put(LogConstant.UID, userBO.getId().toString());
        }
        return super.preHandle(request, response);
    }

    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
        MDC.remove(LogConstant.UID);
        super.postHandle(request, response);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) {
        //获取请求头token
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("access_token");
        if (token == null) {
            handlerException(servletResponse, ResultEnum.ERR_TOKEN.getCode(), ResultEnum.ERR_TOKEN.getMessage());
        }
        AuthenticationToken authenticationToken = new JwtToken(token);
        try {
            getSubject(servletRequest, servletResponse).login(authenticationToken);
            UserBO userBO = (UserBO) SecurityUtils.getSubject().getPrincipal();
            if (userBO != null) {
                MDC.put(LogConstant.UID, userBO.getId().toString());
            }
        } catch (Exception e) {
            handlerException(servletResponse, ResultEnum.ERR_TOKEN.getCode(), ResultEnum.ERR_TOKEN.getMessage());
            return false;
        }
        return true;

    }

    /**
     * 处理过滤器异常
     *
     * @param response
     * @param code
     * @param message
     */
    private void handlerException(ServletResponse response, int code, String message) {
        try {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setStatus(HttpStatus.OK.value());
            httpResponse.setContentType("application/json;charset=utf-8");
            ResponseBase responseBase = new ResponseBase();
            responseBase.setCode(code);
            responseBase.setMessage(message);
            httpResponse.getWriter().write(JSONUtil.toJsonStr(responseBase));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

}



